﻿using Common;
using Microsoft.Extensions.Logging;
using Orleans.Core;
using Orleans.Runtime;
using Orleans;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Server.Impl;

namespace Server
{
    /// <summary>
    /// AGV的侦听服务
    /// </summary>
    public class ListenerService : GrainService
    {
        private readonly IGrainFactory GrainFactory;
        private bool run = true;
        public ListenerService(IGrainIdentity id, Silo silo, ILoggerFactory loggerFactory, IGrainFactory grainFactory) : base(id, silo, loggerFactory)
        {
            GrainFactory = grainFactory;
        }


        public override Task Init(IServiceProvider serviceProvider)
        {
            //初始化数据 
            return base.Init(serviceProvider);
        }

        public override async Task Start()
        {
            await base.Start();
            UdpClient udpClient = new UdpClient(5000);
            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 0);
            while (run)
            {
                try
                {
                    byte[] buffer = udpClient.Receive(ref iPEndPoint);
                    string ip = iPEndPoint.Address.ToString();
                    //解析指令
                    AgvReceiveData? data = Agv指令.解析指令(buffer);
                    if (data != null && data.Value.AgvID>0)
                    {
                        //异步处理，不要卡udp
                         _= Task.Run(() =>
                        {
                            var agvGrain = GrainFactory.GetGrain<IAgv>(data.Value.AgvID); 
                            _ = agvGrain.处理数据(data.Value.Status, data.Value.X, data.Value.Y, data.Value.UpFull, data.Value.DownFull, ip);
                        }); 
                    }
                }
                catch { }
            }
            udpClient.Close();
        }

        public override Task Stop()
        {
            run = false;
            return base.Stop();
        }

 
    }
}
